package org.bangumibuddy.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.bangumibuddy.entity.RssEntity;
import org.bangumibuddy.mapper.RssMapper;
import org.bangumibuddy.pojo.DownloadInfo;
import org.bangumibuddy.pojo.RssDownloadInfo;
import org.bangumibuddy.service.DownloadService;
import org.bangumibuddy.service.RssService;
import org.bangumibuddy.service.TorrentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RssServiceImpl implements RssService {

    @Autowired
    RssMapper rssMapper;

    @Autowired
    TorrentService torrentService;

    @Override
    public boolean isRssSubscribed(String rssUrl) {
        RssEntity rssByURL = rssMapper.getRssByURL(rssUrl);
        return rssByURL != null;
    }

    @Override
    public List<RssDownloadInfo> getRssDownloadInfoByAnimeId(Long animeId) {
        List<RssEntity> rssByAnimeId = rssMapper.getRssByAnimeId(animeId);
        List<RssDownloadInfo> infos = new ArrayList<>();
        for (RssEntity rssEntity :rssByAnimeId)
        {
            List<DownloadInfo> downloadInfoByRssId = torrentService.getDownloadInfoByRssId(rssEntity.getId());
            RssDownloadInfo rssDownloadInfo = new RssDownloadInfo();
            rssDownloadInfo.setId(rssEntity.getId());
            rssDownloadInfo.setUrl(rssEntity.getUrl());
            rssDownloadInfo.setRssName(rssEntity.getName());
            rssDownloadInfo.setIncludePatterns(rssEntity.getIncludePatterns());
            rssDownloadInfo.setExcludePatterns(rssEntity.getExcludePatterns());
            rssDownloadInfo.setDownloadInfos(downloadInfoByRssId);
            infos.add(rssDownloadInfo);
        }

        return infos;
    }
}
